//积分运算处理
//1.定义不同分段链表

var goods_0 =[2,3,4,5,14];    
var goods_1 =[5,5,7,8,14];
var goods_2 =[8,8,10,11,14];
var goods_3 =[10,10,12,13,14];
var goods_4 =[12,14,16,18,14];
var goods_5 =[20,25,30,35,14];
var goods_6 =[80,75,65,60,16];
// var goods_list=['狗年生效酒' = goods_0,
//                 '窖藏1988' = goods_1,
//                 '金钻习酒' =  goods_2,
//                 '蓝习酒' =  goods_3,
//                 '老习酒' = goods_4,
//                 '品鉴酒' = goods_5,
//                 '空空如也' = goods_6];
var goods_list = [goods_0,goods_1,goods_2,goods_3,goods_4,goods_5,goods_6];

function getLevel(score){
    var level = -1;
    if(score>100000){
        level = 4;
    }else if(score>4000){
        level = 3;
    }else if(score>30000){
        level = 2;
    }else if(score>20000){
        level = 1;
    }else if(score>10000){
        level = 0;
    }else{
        console.log('积分不足')
    }

    return level;
}

function GetProb(score){
    //返回每种酒的概率
    var list=[];
    var level = getLevel(score);
    if(level<1){
        return 0;
    }
    for(var i=0;i<7;i++){
        list[i] = goods_list[i][level];
    }

    list.forEach(element => {
        console.log(element);
    });

    var val = getRandNum(list);
    var index = checkNum(list,val);
    var item = getItem(index);
    console.log("产品："+item);

    return item;
};


function getRandNum(list){
    var total = 0;
    console.log('-------概率区间');
    list.forEach(element => {
        total +=(element/100); //计算总概率值
        console.log(total);
    });
    console.log('-------概率区间');
    var rand = Math.random();
    var r = rand * total;   //取一个随即数，乘以总概率，映射到总概率值的区间内
    total = 0;
    for(var i=0;i<list.length;i++){
        total +=(list[i]/100);
        if(total>r){
            console.log(i+" "+total+"  "+r);
            return list[i];
        }
    }
    return list[list.length-1];
}

function getItem(index){
    var item = '空空如也';
    switch(index){
        case 0:
            item = '狗年生效酒';
            break;
        case 1:
            item = '窖藏1988';
            break;
        case 2:
            item = '金钻习酒';
            break;
        case 3:
            item = '蓝习酒';
            break;
        case 4:
            item = '老习酒';
            break;
        case 5:
            item = '品鉴酒';
            break;
        case 6:
            item = '空空如也';
            break;
    }
    return item;
}

//匹配得到对应index
function checkNum(list,val){
    for(var i=0;i<list.length;i++){
        if(val==list[i]){
            return i;
        }
    }
}

module.exports = GetProb;